//
// validate.js
// Simple function to validate forms based on pre-defined´s regex.
// Simple add a attribute to your form like: validate="required"
//

// Avaiable regexs
var DDD_VALIDATE_REGEXS = {
  required: /[a-zA-Z1-9]/i,
  email: /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/,
  brazilian_date: /^([0]?[1-9]|[1|2][0-9]|[3][0|1])[./-]([0]?[1-9]|[1][0-2])[./-]([0-9]{4}|[0-9]{2})$/
}

var DDD_VALIDATE_MESSAGES = {
  required: "Field needs to be filled.",
  email: "Provide a valid e-mail.",
  brazilian_date: "Invalid date format."
}

//
// Function to validate. 
// Returns an object with two arrays: fields_ids and messages.
//
function ddd_validate() {
  var ret_obj = {
    fields_ids: [],
    messages: []
  };

  $("*[validate]").each(function(event) {
    var filter_name = $(this).attr("validate");
    var filter = DDD_VALIDATE_REGEXS[filter_name];
    var field_value = $(this).val();

    if ( (!filter.test(field_value)) || (is_null(field_value)) ) { 
      ret_obj.fields_ids.push($(this).attr("id")); 
      ret_obj.messages.push(DDD_VALIDATE_MESSAGES[filter_name]);
    } 
  });  

  if (ret_obj.fields_ids.length > 0) { return ret_obj; }
  else { return true; }
}
